//
//  EFADeviceVC.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/7.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFADeviceVC.h"
#import <MJRefresh.h>
#import <UIScrollView+EmptyDataSet.h>
#import "EFADeviceTCell.h"
#import "EFADeviceMapVC.h"
#import "EFADeviceInfoVC.h"
#import "EFAModel.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "EFAPjtDeviceAddVC.h"
#import "EFADeviceResultsTVC.h"
#import "UIColor+XDHex.h"
#import "UIImage+XDAdd.h"
#import "UIBarButtonItem+Badge.h"

@interface EFADeviceVC ()<UITableViewDelegate, UITableViewDataSource, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource, EFADeviceTCellDelegate, UISearchResultsUpdating, UISearchBarDelegate, UISearchControllerDelegate>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
//@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer
@property (strong, nonatomic) UISearchController *searchController;
@property (strong, nonatomic) UIBarButtonItem *mapBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *filterBarBtnItem;

@property (strong,   nonatomic) NSArray *typeArray;
@property (assign,   nonatomic) NSInteger currentTypeId;
@property (readonly, nonatomic) NSArray<EFADeviceListItem *> *deviceArray;
@property (strong,   nonatomic) EFADeviceModel *deviceModel;
@end

static NSString *const kReuseCellId = @"EFADeviceTCell";
//static NSInteger const kRequestUserSize = 20;

@implementation EFADeviceVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initLogicData];
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return self.project_id;
}
- (void)initLogicData {
    if (!self.project_id) {
        self.deviceModel = [EFAModel sharedInstance].deviceModel;
    }
}
- (void)initNavigationBar {
    self.navigationItem.title = self.project_name ? self.project_name : @"设备";
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_map"] style:UIBarButtonItemStylePlain target:self action:@selector(mapBarBtnTapped:)];
    self.navigationItem.rightBarButtonItems = @[self.mapBarBtnItem, self.filterBarBtnItem];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:nil action:nil];
}
- (void)initSubViews {
    self.definesPresentationContext = YES;  ///< 这里会影响到搜索结果页面的下拉刷新那里的偏移量
    if (@available(iOS 11.0, *)) {
        self.navigationItem.searchController = self.searchController;
    } else {
        UIView *headerBgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44)];
        [headerBgView addSubview:self.searchController.searchBar];
        self.tableView.tableHeaderView = headerBgView;
        //    self.tableView.tableHeaderView = self.searchController.searchBar; ///< 直接设置为headerview，体验最好，但是mjrefresh会受到影响，蛋疼
    }
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 67.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;

    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    //    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有设备" attributes:dic];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"global_empty"];
}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//        return self.deviceModel.device_list.count;
    return self.deviceArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    EFADeviceTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.row < self.deviceArray.count) {
        [cell configViewWithDeviceListItem:self.deviceArray[indexPath.row]];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}

//点击cell执行方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row < self.deviceArray.count) {
        [self jumpToDeviceInfoWithDeviceListItem:self.deviceArray[indexPath.row]];
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - UISearchResultsUpdating
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    NSString *searchString = searchController.searchBar.text;
    NSLog(@"输入的搜索词语是%@", searchString);
    if (!searchString.length) {
        return;
    }
    
    // hand over the filtered results to our search results table
    EFADeviceResultsTVC *tableController = (EFADeviceResultsTVC *)self.searchController.searchResultsController;
    tableController.keywords = searchString;
    tableController.project_id = self.project_id;
    [tableController refreshNewData];
}

#pragma mark - UISearchControllerDelegate
- (void)didPresentSearchController:(UISearchController *)searchController {
//    CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
//    CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
//
//    if (self.project_id) {
//        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight, 0, 0, 0);
//    } else {
//        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight, 0, tabHeight, 0);
//    }
}
- (void)didDismissSearchController:(UISearchController *)searchController {
//    self.searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    
//    CGFloat statusHeight = CGRectGetHeight([[UIApplication sharedApplication] statusBarFrame]);
//    CGFloat navHeight = CGRectGetHeight(self.navigationController.navigationBar.frame);
//    CGFloat tabHeight = CGRectGetHeight(self.tabBarController.tabBar.frame);
//    
//    if (self.project_id) {
//        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight + navHeight, 0, 0, 0);
//    } else {
//        self.tableView.contentInset = UIEdgeInsetsMake(statusHeight + navHeight, 0, tabHeight, 0);
//    }
    
//    [self.tableView setContentOffset:CGPointMake(0, -statusHeight-navHeight) animated:YES];
}
#pragma mark - EFADeviceTCellDelegate
- (void)deviceTCell:(EFADeviceTCell *)cell deviceNoteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    if (indexPath.row < self.deviceArray.count) {
        EFAPjtDeviceAddVC *vc = [[EFAPjtDeviceAddVC alloc] initWithViewType:EFAPjtDeviceAddVCTypeDetail];
        vc.deviceItem = self.deviceArray[indexPath.row];
        [self showViewController:vc sender:nil];
    }
}

#pragma mark - event response
- (void)mapBarBtnTapped:(UIBarButtonItem *)item {
    EFADeviceMapVC *vc = [[EFADeviceMapVC alloc] init];
//    vc.device_list = self.deviceModel.device_list;
    [self showViewController:vc sender:nil];
}
- (void)filterBarBtnTapped:(UIBarButtonItem *)item {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    for (NSDictionary *dic in self.typeArray) {
        [alertVC addAction:[UIAlertAction actionWithTitle:dic[@"typeName"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            self.currentTypeId = [dic[@"typeId"] integerValue];
            [self refreshWholeView];
        }]];
    }
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - private methods
- (void)jumpToDeviceInfoWithDeviceListItem:(EFADeviceListItem *)item {
    EFADeviceInfoVC *vc = [[EFADeviceInfoVC alloc] init];
    vc.deviceId = item.efairydevice_id;
    vc.device_name = item.efairydevice_name;
    [self showViewController:vc sender:nil];
}
- (void)refreshWholeView {
    //    // 尾部加载更多的显示
    //    if (self.userList.totalLoad) {
    //        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    //    } else {
    //        [self.tableView.mj_footer resetNoMoreData];
    //    }
    
    self.filterBarBtnItem.badgeValue = [NSString stringWithFormat:@"%ld", (unsigned long)self.deviceArray.count];
    self.filterBarBtnItem.badgeOriginY = 4;
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestDeviceListWithHeader:isHeader];
}

- (EFADeviceModel *)deviceListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.deviceModel;
    }
    
    EFADeviceModel *temp = [EFADeviceModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    if (!temp) {
        return self.deviceModel;
    }
    
    if (AddMore && self.deviceModel) {
        [self.deviceModel addMoreWithData:temp];
    } else {
        self.deviceModel = temp;
    }
    return self.deviceModel;
}

#pragma mark - network request
- (void)requestDeviceListWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
//    NSInteger startIndex = isHeader ? 0 : self.deviceModel.device_list.count;
//    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
//                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token
////                           @"efairyproject_id" : @(1)
//                           };
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id) forKey:@"efairyuser_id"];
    [pars setObject:[EFAModel sharedInstance].loginInfo.access_token forKey:@"access_token"];
    if (self.project_id) {
        [pars setObject:@(self.project_id) forKey:@"efairyproject_id"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备列表：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if (self.project_id) {
            [self deviceListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            self.deviceModel = [[EFAModel sharedInstance] deviceModelWithDictionary:responseObject];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}

#pragma mark - getters and setters
- (UISearchController *)searchController {
    if (!_searchController) {
        EFADeviceResultsTVC *tvc = [[EFADeviceResultsTVC alloc] init];
        _searchController = [[UISearchController alloc] initWithSearchResultsController:tvc];
        _searchController.searchResultsUpdater = self; ///< 设置UISearchControllerDelegate协议代理
        _searchController.dimsBackgroundDuringPresentation = YES;///<是否添加半透明覆盖层
        _searchController.hidesNavigationBarDuringPresentation = YES;///< 是否隐藏导航栏
        _searchController.delegate = self;
        _searchController.searchBar.delegate = self;
        _searchController.searchBar.placeholder = @"输入设备昵称或UUID";
        
        if (@available(iOS 11.0, *)) {
            ;
        } else {
            UIImage* searchBarBg = [UIImage xd_getImageWithColor:[UIColor whiteColor] andHeight:1.0f];
            [_searchController.searchBar setBackgroundImage:searchBarBg forBarPosition:UIBarPositionAny barMetrics:UIBarMetricsDefault];
            _searchController.searchBar.barTintColor = [UIColor whiteColor];
            UITextField *searchField = [_searchController.searchBar valueForKey:@"searchField"];
            if (searchField) {
                [searchField setBackgroundColor:[UIColor xd_colorWithHex:0xEEEEEE]];
                searchField.layer.cornerRadius = 4.0f;
                searchField.layer.masksToBounds = YES;
            }
        }
        
        [_searchController.searchBar sizeToFit];
        _searchController.searchBar.frame = CGRectMake(0, 0, CGRectGetWidth([UIScreen mainScreen].bounds), 44);
    }
    return _searchController;
}
- (UIBarButtonItem *)mapBarBtnItem {
    if (!_mapBarBtnItem) {
        _mapBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"device_map"] style:UIBarButtonItemStylePlain target:self action:@selector(mapBarBtnTapped:)];
    }
    return _mapBarBtnItem;
}
- (UIBarButtonItem *)filterBarBtnItem {
    if (!_filterBarBtnItem) {
        _filterBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"msg_filter"] style:UIBarButtonItemStylePlain target:self action:@selector(filterBarBtnTapped:)];
    }
    return _filterBarBtnItem;
}
- (NSArray *)typeArray {
    if (!_typeArray) {
        _typeArray = @[@{@"typeId" : @(0), @"typeName" : @"全部"},
                       @{@"typeId" : @(1), @"typeName" : @"正常"},
                       @{@"typeId" : @(2), @"typeName" : @"故障"},
                       @{@"typeId" : @(3), @"typeName" : @"报警"}];
    }
    return _typeArray;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}
- (NSArray<EFADeviceListItem *> *)deviceArray {
    switch (self.currentTypeId) {
        case 1:
            return self.deviceModel.normalDeviceArray;
            break;
        case 2:
            return self.deviceModel.faultDeviceArray;
            break;
        case 3:
            return self.deviceModel.alarmDeviceArray;
            break;
        default:
            return self.deviceModel.device_list;
            break;
    }
}
@end
